import koa from 'koa';
import bodyParser from 'koa-bodyparser';
import router from './router';
import jwt from './lib/jwt';
import logger from './config/log4.config';
import bcrypt from './lib/bcrypt';
import validator from 'validator';
import cors from 'koa2-cors';
import { validatorRouterLiving } from './middleware/validatorRouterLiving';
import { createRequestCookie } from './middleware/cookie';
import { success, error } from './lib/utils';

const app = new koa();

app.context.jwt = jwt;
app.context.logger = logger;
app.context.bcrypt = bcrypt;
app.context.success = success;
app.context.error = error;
app.context.validator = validator;


app.use(async function(ctx, next) {
  try {
    await next()
  }catch(err) {
    ctx.logger.error(`${ctx.method} ${ctx.path}`, err.message);
    ctx.status = err.status;
    ctx.body = err.message;
  }
})

app.use(bodyParser());
app.use(cors());
app.use(createRequestCookie);

app.use(async (ctx, next) => {

  ctx.logger.info(`${ctx.method} ${ctx.path}`, {
    query: ctx.query,
    body: ctx.request.body
  });

  // 设置响应头
  ctx.set('Content-Type', 'application/json;charset: UTF-8');
  await next();
  console.log(ctx);
  ctx.logger.info({
    status: 200,
    body: ctx.body
  });
});

app.use(validatorRouterLiving);
app.use(router.routes());
app.use(router.allowedMethods());

export default app;



